package com.gzw.dms.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.design.widget.NavigationView;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.gson.reflect.TypeToken;
import com.gzw.dms.MyApplication;
import com.gzw.dms.R;
import com.gzw.dms.UpdateManager;
import com.gzw.dms.adapter.ImageAdapter;
import com.gzw.dms.adapter.MainGVAdapter;
import com.gzw.dms.adapter.SelectDriverAdapter;
import com.gzw.dms.base.BaseActivity;
import com.gzw.dms.base.PermissionActivity;
import com.gzw.dms.bean.AppInfo;
import com.gzw.dms.bean.Constant;
import com.gzw.dms.bean.DriverInfo;
import com.gzw.dms.bean.OrderNumberInfo;
import com.gzw.dms.bean.UserInfo;
import com.gzw.dms.map.MapActivity;
import com.gzw.dms.map.VehicleActivity;
import com.gzw.dms.utils.HttpUtils;
import com.gzw.dms.utils.JsonUtil;
import com.gzw.dms.utils.T;
import com.gzw.dms.utils.UrlUtils;
import com.jauker.widget.BadgeView;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HomeActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener {
    private Context mContext;
    private GridView gv;
    private List<String> lsFuncs;
    private NavigationView navigationView;
    private TextView tv_name, tv_accunt, tv_bbh;
    private String NowVersion;
    private Toolbar toolbar;
    private DrawerLayout drawer;
    private ActionBarDrawerToggle toggle;
    private long exitTime = 0;
    private List<OrderNumberInfo> lsMapInfo = new ArrayList<>();
    private final int SDK_PERMISSION_REQUEST = 127;
    private String permissionInfo;
    private LocationClient mLocationClient;
    private String sure = "NO";
    private String first = "1";
    private UserInfo userInfo;
    private String[] itemList={""};//列表

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_home);
        PushManager.startWork(getApplicationContext(), PushConstants.LOGIN_TYPE_API_KEY, "fM7HqL5MbOl5UUWPB6nSsLNa");
        getPersimmions();

    }

    @Override
    protected void initViews() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        gv = (GridView) findViewById(R.id.gv);
        navigationView = (NavigationView) findViewById(R.id.nav_view);
        View headerView = navigationView.getHeaderView(0);
        tv_name = (TextView) headerView.findViewById(R.id.nav_userName);
        tv_accunt = (TextView) headerView.findViewById(R.id.nav_accunt);
        tv_bbh = (TextView) headerView.findViewById(R.id.nav_bbh);
        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

    }

    @Override
    protected void initData() {
        SignShipOrder signShipOrder = new SignShipOrder();
        signShipOrder.execute();
        mContext = this;
        lsFuncs = new ArrayList<>();
        userInfo = MyApplication.getUserInfo();
        lsFuncs = userInfo.getUserAppRole();

        if (lsFuncs == null || lsFuncs.size()==0) {
            lsFuncs = new ArrayList<>();

        }else {
            getView();
        }
        tv_name.setText(MyApplication.getUserInfo().getRealName());
        tv_accunt.setText(MyApplication.getUserInfo().getUsername());
        NowVersion = getVersion();
        tv_bbh.setText("版本号:" + NowVersion);
        toolbar.setTitle("首页");
        setSupportActionBar(toolbar);
        toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();
        cheakUpDate();

//        initGPS();
    }

    @Override
    protected void initEvents() {

        gv.setOnItemClickListener(new myOnItemClick());
        navigationView.setNavigationItemSelectedListener(this);


    }
    private void initGPS() {
        LocationManager locationManager = (LocationManager) this
                .getSystemService(Context.LOCATION_SERVICE);
        // 判断GPS模块是否开启，如果没有则开启
        if (!locationManager
                .isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
            Toast.makeText(HomeActivity.this, "请打开GPS",
                    Toast.LENGTH_SHORT).show();
            AlertDialog.Builder dialog = new AlertDialog.Builder(this);
            dialog.setMessage("请打开GPS,否则系统无法正常进行！");
            dialog.setPositiveButton("确定",
                    new android.content.DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {

                            // 转到手机设置界面，用户设置GPS
                            Intent intent = new Intent(
                                    Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(intent, 0); // 设置完成后返回到原来的界面

                        }
                    });
            dialog.setNeutralButton("取消", new android.content.DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface arg0, int arg1) {
                    arg0.dismiss();
                }
            } );
            dialog.show();
        } else {
            // 弹出Toast
//          Toast.makeText(TrainDetailsActivity.this, "GPS is ready",
//                  Toast.LENGTH_LONG).show();
//          // 弹出对话框
//          new AlertDialog.Builder(this).setMessage("GPS is ready")
//                  .setPositiveButton("OK", null).show();
        }
    }

    private void getView() {
        MainGVAdapter adapter = new MainGVAdapter(mContext, lsFuncs, lsMapInfo);
        gv.setAdapter(adapter);
    }



    class myOnClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {


                default:
                    break;
            }
        }
    }

    class myOnItemClick implements AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String b = parent.toString();
            Intent mIntent = new Intent();
            switch (lsFuncs.get(position)) {
                case "11":
//                    mIntent.setClass(mContext, OrderActivity.class);
                    mIntent.setClass(mContext, MonitActivity.class);

                    startActivity(mIntent);
                    break;
                case "4":
//                    mIntent.setClass(mContext, BackActivity.class);
                    mIntent.setClass(mContext, Home1Activity.class);

                    startActivity(mIntent);
                    break;

                case "7":
                    mIntent.setClass(mContext, UserAdministrationActivity.class);
                    startActivity(mIntent);
                    break;
                case "8":
                    mIntent.setClass(mContext, MySelfActivity.class);
                    startActivityForResult(mIntent, 2);
                    break;
                case "9":
                    mIntent.setClass(mContext, MessageActivity.class);
//                    mIntent.setClass(mContext, OrderChangeActivity.class);
                    startActivityForResult(mIntent, 3);
                    break;
                case "17":
                    mIntent.setClass(mContext, MonitActivity.class);

                    startActivity(mIntent);
                    break;

            }
        }
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        int id = item.getItemId();
        int i = 0;
        if (id == R.id.nav_switchAccount) {
            SharedPreferences sharedPreferences = getSharedPreferences(Constant.USERINFO_KEY,
                    Context.MODE_PRIVATE);
            SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.putBoolean(Constant.IS_USER_LOGIN_KEY, false);
            edit.commit();
            Intent intent = new Intent();
            intent.setClass(mContext, LoginActivity.class);
            startActivity(intent);
            finish();
            return true;
        } else if (id == R.id.nav_signOut) {
            SharedPreferences sharedPreferences = getSharedPreferences(Constant.USERINFO_KEY,
                    Context.MODE_PRIVATE);
            SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.putBoolean(Constant.IS_USER_LOGIN_KEY, false);
            edit.commit();
            finish();
        }

        return true;
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(this, "再按一次退出程序。", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                exitApp();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */

    private void cheakUpDate() {
        ShowVersionTask showVersionTask = new ShowVersionTask();
        showVersionTask.execute();
    }

    public class ShowVersionTask extends AsyncTask<String, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {

        }

        protected String doInBackground(String... params) {
            return HttpUtils.doPost(UrlUtils.getInstance().getJavaUrl("getAppVersion"), "");
        }

        @Override
        protected void onPostExecute(final String result) {

            if (result == null || result.length() == 0) {
                T.showShort(mContext, "连接服务器异常。");
            }
            if (result.indexOf("successMsg") > 0) {
                String successMsg = JsonUtil.getMsg(result, "successMsg");
                AppInfo appInfo = JsonUtil.getPerson(successMsg, AppInfo.class);
                NowVersion = getVersion();
                if (NowVersion.equals(appInfo.getVersion())) {
//                    T.showShort(mContext, "未发现新版本");

                } else {
                    itemList = appInfo.getMessage();
                    UpdateManager mUpdateManager = new UpdateManager(mContext);
                    mUpdateManager.checkUpdateInfo(itemList);
                }

            } else if (result.indexOf("errorMsg") > 0) {
                String errorMsg = JsonUtil.getMsg(result, "errorMsg");
                T.showShort(mContext, errorMsg);
            }
        }

    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public String getVersion() {
        try {
            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (sure.equals("NO")){
            initGPS();
        }
        if (resultCode == 2) {
            Intent sintent = new Intent();
            sintent.setClass(mContext, LoginActivity.class);
            startActivity(sintent);
            finish();
        } else if (requestCode == 3) {
            SignShipOrder signShipOrder = new SignShipOrder();
            signShipOrder.execute();
        }

    }

    public class SignShipOrder extends AsyncTask<DriverInfo, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {

        }

        protected String doInBackground(DriverInfo... params) {
            Map<String, Object> map = new HashMap<>();
            UserInfo userInfo = MyApplication.getUserInfo();
            map.put("userInfo", userInfo);
            String json = JsonUtil.toJson(map);
            return HttpUtils.doPost(UrlUtils.getInstance().getJavaUrl("appGetMessageCount"), "json=" + json);
        }

        @Override
        protected void onPostExecute(final String result) {
            if (isNull(result)) {
                T.showShort(mContext, "连接服务器异常");
            } else {

                if (result.indexOf("errorMsg") > 0) {
                    String errorMsg = JsonUtil.getMsg(result, "errorMsg");
                    T.showShort(mContext, errorMsg);
                } else {
                    String successMsg = JsonUtil.getMsg(result, "successMsg");
                    final List<OrderNumberInfo> lsMap = JsonUtil.getPersons(successMsg, new TypeToken<List<OrderNumberInfo>>() {
                    }.getType());
                    lsMapInfo = lsMap;
                    getView();
                    if (first.equals("1")){
                        AppIsHaveGps appIsHaveGps = new AppIsHaveGps();
                        appIsHaveGps.execute();
                        first = "0";
                    }

                }
            }
        }

        @Override
        protected void onCancelled() {


        }
    }


    public class AppIsHaveGps extends AsyncTask<DriverInfo, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {

        }

        protected String doInBackground(DriverInfo... params) {
            Map<String, Object> map = new HashMap<>();
            UserInfo userInfo = MyApplication.getUserInfo();
            map.put("userInfo", userInfo);
            String json = JsonUtil.toJson(map);
            return HttpUtils.doPost(UrlUtils.getInstance().getJavaUrl("appIsHaveGps"), "json=" + json);
        }

        @Override
        protected void onPostExecute(final String result) {
            if (isNull(result)) {
            } else {

                if (result.indexOf("errorMsg") > 0) {
                    String errorMsg = JsonUtil.getMsg(result, "errorMsg");
                    T.showShort(mContext, errorMsg);
                } else {
                    String successMsg = JsonUtil.getMsg(result, "successMsg");
                    sure = successMsg;
                    if (sure.equals("NO")){
                        initGPS();
                    }
                }
            }
        }

        @Override
        protected void onCancelled() {

        }
    }


    @TargetApi(23)
    private void getPersimmions() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            /***
             * 定位权限为必须权限，用户如果禁止，则每次进入都会申请
             */

            // 定位精确位置
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            }

            /*
			 * 读写权限和电话状态权限非必要权限(建议授予)只会申请一次，用户同意或者禁止，只会弹一次
			 */
            // 读写权限
            if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissionInfo += "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny \n";
            }
            // 读取电话状态权限
            if (addPermission(permissions, Manifest.permission.READ_PHONE_STATE)) {
                permissionInfo += "Manifest.permission.READ_PHONE_STATE Deny \n";
            }

            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }
        }
    }

    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale(permission)) {
                return true;
            } else {
                permissionsList.add(permission);
                return false;

            }

        } else {
            return true;
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // TODO Auto-generated method stub
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

//        switch (requestCode) {
//            case SDK_PERMISSION_REQUEST:
//                if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
//                    // 获取到权限，作相应处理（调用定位SDK应当确保相关权限均被授权，否则可能引起定位失败）
//                    mLocationClient = ((MyApplication) getApplication()).mLocationClient;
//                    initLocation();
//                }else {
//                        // 没有获取到权限，做特殊处理
//                    T.showShort(mContext,"定位权限未开启，请先开启定位权限！");
//                }
//                break;
//            default:
//                break;
//        }
    }


    //设置定位选项
    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span = 1000 * 30;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认false，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        mLocationClient.start();

        mLocationClient.setLocOption(option);


    }



}
